<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Observers;

use App\Models\UserAddress;

class UserAddressObserver
{
    public function saving(UserAddress $address)
    {
        if ($address->is_default == 1) {
            UserAddress::query()->where('user_id', $address->user_id)
                ->where('id', '!=', $address->id) // 排除自身（如果是更新操作）
                ->update(['is_default' => 0]);
        }
        if ($address->getOriginal('is_default') == 1 && $address->is_default == 0) {
            $newDefault = UserAddress::query()
                ->where('user_id', $address->user_id)
                ->where('id', '<>', $address->id)
                ->latest()
                ->first();
            if ($newDefault) {
                $newDefault->update(['is_default' => 1]);
            }
        }
    }

    public function deleting(UserAddress $userAddress)
    {
    }

    /**
     * Handle the UserAddress "updated" event.
     */
    public function updated(UserAddress $userAddress)
    {
    }

    /**
     * Handle the UserAddress "deleted" event.
     */
    public function deleted(UserAddress $userAddress)
    {
        if ($userAddress->is_default == 1) {
            // 自动将用户最新地址设为默认
            $newDefault = UserAddress::query()
                ->where('user_id', $userAddress->user_id)
                ->latest()
                ->first();
            if ($newDefault) {
                $newDefault->update(['is_default' => 1]);
            }
        }
    }

    /**
     * Handle the UserAddress "restored" event.
     */
    public function restored(UserAddress $userAddress)
    {
    }

    /**
     * Handle the UserAddress "force deleted" event.
     */
    public function forceDeleted(UserAddress $userAddress)
    {
    }
}
